package com.example.lynandroidbeta

import android.annotation.SuppressLint
import android.app.Activity
import android.app.ActivityManager
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.*
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.example.lynandroidbeta.databinding.MainBinding


class MainActivity : AppCompatActivity() {
    lateinit var binding: MainBinding
    private var messenger: Messenger? = null

    @SuppressLint("DiscouragedPrivateApi", "SetTextI18n")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        bindMyService()
        binding = MainBinding.inflate(layoutInflater).apply {
            setContentView(this.root)
            callback = CallBack {
                startService(Intent(this@MainActivity, MyAidlService::class.java))
                messenger?.send(Message.obtain())
            }
        }
        initReferer()
    }

    private fun initReferer() {
        binding.hello.text = referrer?.toString().orEmpty()
        try {
            val activityClass = Class.forName(("android.app.Activity"))
            val refererField = activityClass.getDeclaredField("mReferrer")
            refererField.isAccessible = true
            val referrer = refererField.get(this)
            binding.hello.text = "${referrer?.toString().orEmpty()}\n$referrer\n${reRealPackage()}"
        } catch (e: Exception) {
            e.printStackTrace()
            startActivity(Intent())
        }
    }

    private fun bindMyService() {
        bindService(
            Intent(this@MainActivity, MyService::class.java),
            object : ServiceConnection {
                override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
                    messenger = Messenger(service)
                }

                override fun onServiceDisconnected(name: ComponentName?) {

                }
            },
            Context.BIND_AUTO_CREATE
        )
    }


    private fun reRealPackage(): String? {
        try {
            val getServiceMethod = ActivityManager::class.java.getMethod("getService")
            val sIActivityManager = getServiceMethod.invoke(null)
            val sGetLaunchedFromUidMethod = sIActivityManager.javaClass.getMethod(
                "getLaunchedFromUid",
                IBinder::class.java
            )
            val sGetActivityTokenMethod = Activity::class.java.getMethod("getActivityToken")
            val binder = sGetActivityTokenMethod.invoke(this) as IBinder
            val uid = sGetLaunchedFromUidMethod.invoke(sIActivityManager, binder) as Int
            return packageManager.getNameForUid(uid)
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return "null"
    }

    fun interface CallBack {
        fun onHelloClick()
    }
}